package cn.ixinjiu.libraryMangement.controller.systemAdmin.bookSort;

import cn.ixinjiu.libraryMangement.entity.BookSort;
import cn.ixinjiu.libraryMangement.service.IBookSortService;
import cn.ixinjiu.libraryMangement.service.impl.BookSortServiceImpl;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * Created by XinChen on 2023-05-22
 *
 * @TODO 分类信息列表
 */
@WebServlet("/booksSortList")
public class BookSortServlet extends HttpServlet {
    private IBookSortService iBookSortService = new BookSortServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置编码格式
        req.setCharacterEncoding("utf-8");
        resp.setHeader("Content-Type", "text/html;charset=utf-8");
        List<BookSort> bookSorts = iBookSortService.bookSorts();
        // 准备返回数据
        JSONArray jsonArray = new JSONArray(); // 中转站
        JSONObject jsonObject = new JSONObject(); // 要返回的json对象
        for (BookSort bookSort : bookSorts) {
            JSONObject jsonData = new JSONObject(); // json数据
            jsonData.put("id", bookSort.getId());
            jsonData.put("name", bookSort.getName());
            jsonData.put("description", bookSort.getDescription());
            jsonArray.add(jsonData);
        }
        // 数据总数
        int count = iBookSortService.count();
        // 添加返回数据
        jsonObject.put("code", 0); // 设置状态码，0正常
        jsonObject.put("data", jsonArray.toArray()); // 设置数据
        jsonObject.put("count", count); // 设置 “共 ？ 条” 数据
        jsonObject.put("msg", "success~"); // 设置提示信息
        // 写入到页面
        PrintWriter out = resp.getWriter();
        out.write(jsonObject.toString());
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
